import React, { useState, useEffect } from 'react';
import { 
  Typography, 
  Table, 
  Button, 
  Tag, 
  Space, 
  Input, 
  Modal, 
  Form, 
  Select,
  Drawer,
  Divider,
  Card,
  Tabs,
  List,
  Avatar,
  Spin
} from 'antd';
import { 
  UserOutlined, 
  EditOutlined, 
  SearchOutlined, 
  PlusOutlined,
  SettingOutlined,
  MessageOutlined,
  HistoryOutlined
} from '@ant-design/icons';
import contactsService from '../api/contactsService';
import chatService from '../api/chatService';

const { Title, Paragraph, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

const ContactsPage = () => {
  const [contacts, setContacts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchText, setSearchText] = useState('');
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [selectedContact, setSelectedContact] = useState(null);
  const [relationshipTypes, setRelationshipTypes] = useState([]);
  const [chatGoals, setChatGoals] = useState([]);
  const [contactHistory, setContactHistory] = useState([]);
  const [historyLoading, setHistoryLoading] = useState(false);

  // 获取联系人数据
  useEffect(() => {
    const fetchContacts = async () => {
      try {
        // 模拟数据 - 实际应用中应使用API
        setTimeout(() => {
          const mockContacts = [
            { 
              id: '1', 
              name: '张三', 
              relationship_type: 'friend', 
              relationship_type_name: '朋友',
              chat_goal: 'social', 
              chat_goal_name: '社交聊天',
              last_interaction: '2025-04-10',
              interaction_frequency: '频繁',
              notes: '大学同学，喜欢谈论体育和电影',
              tags: ['重要', '密友']
            },
            { 
              id: '2', 
              name: '李四', 
              relationship_type: 'colleague', 
              relationship_type_name: '同事',
              chat_goal: 'work_report', 
              chat_goal_name: '工作汇报',
              last_interaction: '2025-04-09',
              interaction_frequency: '每周',
              notes: '项目经理，沟通时注重简洁明了',
              tags: ['工作']
            },
            { 
              id: '3', 
              name: '工作群', 
              relationship_type: 'group', 
              relationship_type_name: '群聊',
              chat_goal: 'information_sharing', 
              chat_goal_name: '信息共享',
              last_interaction: '2025-04-11',
              interaction_frequency: '每日',
              notes: '项目组工作群，主要用于工作通知和文件共享',
              tags: ['工作', '重要']
            },
            { 
              id: '4', 
              name: '王五', 
              relationship_type: 'client', 
              relationship_type_name: '客户',
              chat_goal: 'maintain_relationship', 
              chat_goal_name: '维系关系',
              last_interaction: '2025-04-05',
              interaction_frequency: '偶尔',
              notes: '潜在客户，对我们的产品有兴趣',
              tags: ['商业', '跟进']
            }
          ];
          setContacts(mockContacts);
          setLoading(false);
        }, 800);
        
        // 实际API调用示例：
        // const contactsData = await contactsService.getContacts();
        // setContacts(contactsData);
        // setLoading(false);
      } catch (error) {
        console.error('获取联系人失败:', error);
        setLoading(false);
      }
    };

    fetchContacts();
  }, []);

  // 获取关系类型和聊天目标
  useEffect(() => {
    const fetchRelationshipData = async () => {
      try {
        // 模拟数据 - 实际应用中应使用API
        setTimeout(() => {
          setRelationshipTypes([
            { id: 'friend', name: '朋友' },
            { id: 'colleague', name: '同事' },
            { id: 'family', name: '家人' },
            { id: 'client', name: '客户' },
            { id: 'superior', name: '上级' },
            { id: 'subordinate', name: '下级' },
            { id: 'group', name: '群聊' }
          ]);
          
          setChatGoals([
            { id: 'social', name: '社交聊天' },
            { id: 'work_report', name: '工作汇报' },
            { id: 'negotiate', name: '协商事务' },
            { id: 'solve_problem', name: '解决问题' },
            { id: 'maintain_relationship', name: '维系关系' },
            { id: 'information_sharing', name: '信息共享' }
          ]);
        }, 500);
        
        // 实际API调用示例：
        // const relationshipTypes = await contactsService.getRelationshipTypes();
        // const chatGoals = await contactsService.getChatGoals();
        // setRelationshipTypes(relationshipTypes);
        // setChatGoals(chatGoals);
      } catch (error) {
        console.error('获取关系数据失败:', error);
      }
    };

    fetchRelationshipData();
  }, []);

  // 查看联系人详情
  const handleViewContact = (contact) => {
    setSelectedContact(contact);
    setDrawerVisible(true);
    
    // 加载联系人的聊天历史记录
    const fetchContactHistory = async () => {
      setHistoryLoading(true);
      try {
        // 模拟数据 - 实际应用中应使用API
        setTimeout(() => {
          const mockHistory = [
            {
              id: '1',
              date: '2025-04-10',
              content: '我们明天10点会议室见。',
              time: '15:30',
              is_self: false
            },
            {
              id: '2',
              date: '2025-04-10',
              content: '好的，我会准时到。',
              time: '15:35',
              is_self: true
            },
            {
              id: '3',
              date: '2025-04-08',
              content: '项目报告完成了吗？',
              time: '09:15',
              is_self: false
            },
            {
              id: '4',
              date: '2025-04-08',
              content: '已经完成，稍后发给你。',
              time: '09:20',
              is_self: true
            }
          ];
          setContactHistory(mockHistory);
          setHistoryLoading(false);
        }, 700);
        
        // 实际API调用示例：
        // const historyData = await chatService.getChatHistory(contact.id, 10);
        // setContactHistory(historyData);
        // setHistoryLoading(false);
      } catch (error) {
        console.error('获取聊天历史失败:', error);
        setHistoryLoading(false);
      }
    };
    
    fetchContactHistory();
  };

  // 编辑联系人
  const handleEditContact = (values) => {
    if (!selectedContact) return;
    
    // 在实际应用中，这里应该调用API更新联系人信息
    const updatedContacts = contacts.map(contact => {
      if (contact.id === selectedContact.id) {
        const relationshipType = relationshipTypes.find(type => type.id === values.relationship_type);
        const chatGoal = chatGoals.find(goal => goal.id === values.chat_goal);
        
        return {
          ...contact,
          relationship_type: values.relationship_type,
          relationship_type_name: relationshipType?.name || '',
          chat_goal: values.chat_goal,
          chat_goal_name: chatGoal?.name || '',
          notes: values.notes,
          tags: values.tags
        };
      }
      return contact;
    });
    
    setContacts(updatedContacts);
    
    // 更新选中的联系人信息
    const updatedContact = updatedContacts.find(contact => contact.id === selectedContact.id);
    setSelectedContact(updatedContact);
    
    // 实际API调用示例：
    // await contactsService.updateRelationship(selectedContact.id, {
    //   relationship_type: values.relationship_type,
    //   chat_goal: values.chat_goal,
    //   notes: values.notes,
    //   tags: values.tags
    // });
  };

  // 过滤联系人
  const filteredContacts = contacts.filter(contact => {
    return (
      contact.name.toLowerCase().includes(searchText.toLowerCase()) ||
      contact.tags.some(tag => tag.toLowerCase().includes(searchText.toLowerCase())) ||
      contact.relationship_type_name.toLowerCase().includes(searchText.toLowerCase()) ||
      contact.chat_goal_name.toLowerCase().includes(searchText.toLowerCase())
    );
  });
  
  // 表格列定义
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <a onClick={() => handleViewContact(record)}>{text}</a>
      ),
    },
    {
      title: '关系类型',
      dataIndex: 'relationship_type_name',
      key: 'relationship_type_name',
    },
    {
      title: '聊天目标',
      dataIndex: 'chat_goal_name',
      key: 'chat_goal_name',
    },
    {
      title: '最近互动',
      dataIndex: 'last_interaction',
      key: 'last_interaction',
    },
    {
      title: '互动频率',
      dataIndex: 'interaction_frequency',
      key: 'interaction_frequency',
    },
    {
      title: '标签',
      key: 'tags',
      dataIndex: 'tags',
      render: tags => (
        <>
          {tags.map(tag => {
            let color = tag.length > 3 ? 'geekblue' : 'green';
            if (tag === '重要') {
              color = 'red';
            }
            return (
              <Tag color={color} key={tag}>
                {tag}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            size="small" 
            icon={<MessageOutlined />}
            onClick={() => window.location.href = `/chat?contact=${record.id}`}
          >
            聊天
          </Button>
          <Button 
            size="small" 
            icon={<SettingOutlined />}
            onClick={() => handleViewContact(record)}
          >
            管理
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Title level={2}>联系人管理</Title>
      <Paragraph>
        管理联系人关系和聊天目标，为每个关系定制交流策略。
      </Paragraph>
      
      {/* 搜索工具栏 */}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <Input 
          placeholder="搜索联系人、标签或关系类型" 
          prefix={<SearchOutlined />} 
          style={{ width: 300 }}
          value={searchText}
          onChange={e => setSearchText(e.target.value)}
        />
      </div>
      
      {/* 联系人列表 */}
      <Table 
        columns={columns} 
        dataSource={filteredContacts} 
        rowKey="id" 
        loading={loading}
        pagination={{ pageSize: 10 }}
      />
      
      {/* 联系人详情抽屉 */}
      <Drawer
        title="联系人详情"
        placement="right"
        width={520}
        onClose={() => setDrawerVisible(false)}
        visible={drawerVisible}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => setDrawerVisible(false)} style={{ marginRight: 8 }}>
              关闭
            </Button>
            <Button 
              type="primary" 
              onClick={() => window.location.href = `/chat?contact=${selectedContact?.id}`}
            >
              开始聊天
            </Button>
          </div>
        }
      >
        {selectedContact && (
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本信息" key="1">
              <div style={{ marginBottom: 24 }}>
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
                  <Avatar size={64} icon={<UserOutlined />} />
                  <div style={{ marginLeft: 16 }}>
                    <Title level={4} style={{ margin: 0 }}>{selectedContact.name}</Title>
                    <div>
                      {selectedContact.tags.map(tag => (
                        <Tag key={tag}>{tag}</Tag>
                      ))}
                    </div>
                  </div>
                </div>
                
                <Card size="small" title="关系设置" style={{ marginBottom: 16 }}>
                  <Form
                    layout="vertical"
                    initialValues={{
                      relationship_type: selectedContact.relationship_type,
                      chat_goal: selectedContact.chat_goal,
                      notes: selectedContact.notes,
                      tags: selectedContact.tags
                    }}
                    onFinish={handleEditContact}
                  >
                    <Form.Item
                      name="relationship_type"
                      label="关系类型"
                      rules={[{ required: true, message: '请选择关系类型' }]}
                    >
                      <Select placeholder="选择关系类型">
                        {relationshipTypes.map(type => (
                          <Option key={type.id} value={type.id}>{type.name}</Option>
                        ))}
                      </Select>
                    </Form.Item>
                    
                    <Form.Item
                      name="chat_goal"
                      label="聊天目标"
                      rules={[{ required: true, message: '请选择聊天目标' }]}
                    >
                      <Select placeholder="选择聊天目标">
                        {chatGoals.map(goal => (
                          <Option key={goal.id} value={goal.id}>{goal.name}</Option>
                        ))}
                      </Select>
                    </Form.Item>
                    
                    <Form.Item
                      name="notes"
                      label="备注"
                    >
                      <Input.TextArea rows={3} placeholder="添加备注信息..." />
                    </Form.Item>
                    
                    <Form.Item
                      name="tags"
                      label="标签"
                    >
                      <Select mode="tags" placeholder="添加标签...">
                        <Option value="重要">重要</Option>
                        <Option value="工作">工作</Option>
                        <Option value="密友">密友</Option>
                        <Option value="家人">家人</Option>
                        <Option value="商业">商业</Option>
                        <Option value="跟进">跟进</Option>
                      </Select>
                    </Form.Item>
                    
                    <Form.Item>
                      <Button type="primary" htmlType="submit">
                        保存
                      </Button>
                    </Form.Item>
                  </Form>
                </Card>
                
                <Card size="small" title="互动统计">
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div>
                      <Text type="secondary">最近互动</Text>
                      <div>{selectedContact.last_interaction}</div>
                    </div>
                    <div>
                      <Text type="secondary">互动频率</Text>
                      <div>{selectedContact.interaction_frequency}</div>
                    </div>
                    <div>
                      <Text type="secondary">总消息数</Text>
                      <div>128</div>
                    </div>
                  </div>
                </Card>
              </div>
            </TabPane>
            
            <TabPane tab="聊天历史" key="2">
              {historyLoading ? (
                <div style={{ textAlign: 'center', padding: '20px 0' }}>
                  <Spin />
                </div>
              ) : (
                <>
                  <List
                    dataSource={contactHistory}
                    renderItem={item => (
                      <List.Item>
                        <List.Item.Meta
                          title={
                            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                              <span>{item.is_self ? '我' : selectedContact.name}</span>
                              <Text type="secondary">{item.date} {item.time}</Text>
                            </div>
                          }
                          description={item.content}
                        />
                      </List.Item>
                    )}
                  />
                  <div style={{ textAlign: 'center', margin: '20px 0' }}>
                    <Button icon={<HistoryOutlined />}>查看更多历史记录</Button>
                  </div>
                </>
              )}
            </TabPane>
          </Tabs>
        )}
      </Drawer>
    </div>
  );
};

export default ContactsPage; 